//
//  CQQauthViewController.swift
//  weibo
//
//  Created by chengqiang on 16/7/21.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit
import SVProgressHUD
class CQQauthViewController: UIViewController {
    
    override func loadView() {
        self.view=webView
        webView.delegate=self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //MARK:- 显示登录界面
        self.view.backgroundColor=UIColor.whiteColor()
        setNavigationBar()
        //MARK：－ 发送网络请求
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        //延迟两秒
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        SVProgressHUD.showWithStatus("正在加载...")
    }
    
    private func setNavigationBar()
    {
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFil")
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        self.navigationItem.title="登录"
    }
    
    
    //MARK:-自动填充账号和密码
    @objc private  func autoFil()
    {
       let jsCode = "document.getElementById('userId').value='15926828542';document.getElementById('passwd').value='ct1993625414'"
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    @objc private func close(){
        
        SVProgressHUD.dismiss()
        //回退到上个控制器
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    private lazy var webView:UIWebView = UIWebView()

}
extension CQQauthViewController:UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("\(urlString)")
        
        if !urlString.hasPrefix(redirect_uri) {
            return true
        }else{
            
            let codeString="code="
            let query = request.URL!.query!
            
            //判断点击的按钮是授权还是取消
            if query.hasPrefix(codeString) {
                print("点击授权")
                let qsQuery = query as NSString
                let code = qsQuery.substringFromIndex(codeString.characters.count)
                CQUserViewModel.shareduserAccountViewModel.loadAccessToken(code, completion: {(error:NSError?)->Void in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("加载AccountToken出错")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                        })
                        return
                    }
                self.close()
                    //跳转到欢迎控界面控制器
                    AppDelegate.switchRootViewController(CQMianController())
                })
//                loadAccessToken(code)
            }else{
                self.close()
            }
            
            
            return false
        }
    }

//    private func loadAccessToken(code:String)
//    {
//        
//        let urlString="https://api.weibo.com/oauth2/access_token"
//        let paraments=[
//            "client_id": client_id,
//            "client_secret": client_secret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": redirect_uri]
//    CQTool.sharedNetworking.POST(urlString, parameters: paraments, progress: nil, success: { (_, resonpnseObject)-> Void  in
//        
//        let dict = resonpnseObject as![String:AnyObject]
//        let userAccont = CQUserAccont(dict: dict)
//        print("usercount   \(userAccont)")
//        }) { (_, error)-> Void in
//            print("error==\(error)")
//            
//        }
//    }
    
}
